<template>
  <!-- 团队总结表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1000"
    draggable
    @close="closeDialog"
    :append-to-body="true"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="160">
      <table
        width="100%"
        cellpadding="0"
        cellspacing="0"
        style="margin: 0 auto"
      >
        <tr>
          <td>
            <table
              border="1"
              class="bordered-table"
              cellpadding="5"
              cellspacing="0"
              width="800px"
              style="height: 450px"
            >
              <thead>
                <tr>
                  <!--<th rowspan="2">序号</th>-->
                  <th rowspan="2">项目</th>
                  <th rowspan="2">内容</th>
                  <th rowspan="2" style="width: 100px">得分</th>
                  <th rowspan="2">满分标准</th>
                </tr>
              </thead>
              <tbody align="center">
                <template v-for="(i, index) in formData.table" :key="index">
                  <tr v-if="isFirstInGroup(index)">
                    <!--<td :rowspan="getRowspan(index)">
                      {{ serialNumbers[index] }}
                    </td>-->
                    <td :rowspan="getRowspan(index)">
                      {{
                        dictionaryStore.filterDictName(
                          "ProblemSummary",
                          i.problemSummary
                        )
                      }}
                    </td>
                    <td align="left">
                      {{ i.subProblemSummary }}
                    </td>
                    <td>
                      <el-input-number
                        v-if="!props.isReadonly"
                        v-model="i.ownPoint"
                        :controls="false"
                        class="centered-input"
                        :min="0"
                        :max="Number(i.fullPoint)"
                      />
                      <span v-else>{{ i.ownPoint }}</span>
                    </td>
                    <td>
                      {{ i.fullPoint }}
                    </td>
                  </tr>
                  <tr v-else>
                    <td align="left">
                      {{ i.subProblemSummary }}
                    </td>
                    <td>
                      <el-input-number
                        v-if="!props.isReadonly"
                        v-model="i.ownPoint"
                        :controls="false"
                        class="centered-input"
                        :min="0"
                        :max="Number(i.fullPoint)"
                      />
                      <span v-else>{{ i.ownPoint }}</span>
                    </td>
                    <td>
                      {{ i.fullPoint }}
                    </td>
                  </tr>
                </template>
                <tr>
                  <td colspan="2" align="center">合计</td>
                  <td>{{ getGrossScore(formData.table) }}</td>
                  <td>
                    {{
                      formData.table.reduce(
                        (accumulator, currentValue) =>
                          accumulator + currentValue.fullPoint,
                        0
                      )
                    }}
                  </td>
                </tr>
              </tbody>
            </table>
          </td>
        </tr>
      </table>
      <el-row>
        <el-col :span="24" style="margin-top: 10px">
          <span style="font-weight: 700; font-size: 18px">评价意见：</span>
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.exceptionContent"
            type="textarea"
            :rows="5"
            placeholder="请输入"
            clearable
          />
          <div v-else>{{ formData.exceptionContent }}</div>
          <div style="font-weight: 600; font-size: 20px; margin-top: 15px">
            90至100分，可以提交改进报告
          </div>
          <div style="font-weight: 600; font-size: 20px">
            低于90分，改进存在缺陷，如果提交需要得到创新SQE批准
          </div>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="success"
          :loading="loading"
          @click="handleSubmit(1)"
          >提 交</el-button
        >
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit(0)"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQ8DD80ADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  ownPoint: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  qualityExceptionId: "",
  qualityExceptionCode: "",
  problemSummaryItemId: "",
  ownPoint: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  exceptionContent: "",
  workOrderId: "",
  table: [],
  isSubmit: 0,
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        qualityExceptionId,
        qualityExceptionCode,
        problemSummaryItemId,
        ownPoint,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        qualityExceptionId,
        qualityExceptionCode,
        problemSummaryItemId,
        ownPoint,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      formData.qualityExceptionId = newVal.qualityProblemId;
      formData.qualityExceptionCode = newVal.qualityProblemCode;
      formData.workOrderId = newVal.id;
      if (newVal.qualityProblemId) {
        getD80(newVal.id);
      } else {
        getD8(newVal.id);
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.qualityExceptionId = "";
  formData.qualityExceptionCode = "";
  formData.problemSummaryItemId = "";
  formData.ownPoint = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.exceptionContent = "";
  formData.workOrderId = "";
  formData.table = [];
  formData.isSubmit = 0;
}

const loading = ref(false);

/** 团队总结保存提交 */
function handleSubmit(state: Number) {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = state == 0 ? "保存" : "提交";
      formData.isSubmit = state;
      await request({
        url: "/qms/q8dd81/saveList",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
onMounted(() => {
  getProblemSummary();
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
async function getProblemSummary() {
  const res = await request({
    url: "/qms/qmsproblemsummaryitem/getList",
    method: "post",
    data: {},
  });
  if (res.code == 200) {
    formData.table = res.data;
  } else {
    formData.table = [];
  }
}
function updateDefectRate(item) {
  // 更新不良率并将其赋值给 formData.table 中的 noaQuantity 字段
  item.noaQuantity = Number(calculateDefectRate(item)); // 确保将不良率转换为数字类型
}
function calculateDefectRate(item) {
  // 计算不良率：问题件数量 / 总数量
  if (item.totalQuantity > 0) {
    return ((item.exceptionQuantity / item.totalQuantity) * 100).toFixed(2); // 保留两位小数
  }
  return 0; // 当总数量为0时，不良率为0%
}
function isFirstInGroup(index) {
  return (
    index === 0 ||
    formData.table[index].problemSummary !==
      formData.table[index - 1].problemSummary
  );
}
function getRowspan(index) {
  let count = 1;
  const currentType = formData.table[index].problemSummary;
  while (
    index + count < formData.table.length &&
    formData.table[index + count].problemSummary === currentType
  ) {
    count++;
  }
  return count;
}
//计算得分总数
function getGrossScore(arr) {
  let sum = 0;
  arr.forEach((item) => {
    if (Number(item.ownPoint)) {
      sum += Number(item.ownPoint);
    }
  });
  return sum;
}
//获取D80
function getD80(id: string) {
  request({
    url: "/qms/q8dd81/getD80",
    method: "post",
    data: {
      qualityExceptionId: id,
    },
  }).then((res) => {
    if (res.code == 200 && res.data != null) {
      if (res.data.table) {
        formData.table = res.data.table;
      }
      formData.exceptionContent = res.data.exceptionContent;
    }
  });
}
//通过质量问题id获取评分信息
function getD8(id: string) {
  request({
    url: "/qms/q8dworkorder/queryWorkList",
    method: "post",
    data: {
      qualityProblemId: id,
      exceptionBusinessType: 19,
    },
  }).then((res) => {
    if (res.code == 200 && res.data.length > 0) {
      if (res.data[0].table) {
        formData.table = res.data[0].table;
      }
      formData.exceptionContent = res.data[0].exceptionContent;
    }
  });
}
//序号
const mergedRowSpans = computed(() => {
  const rows = [...formData.table];
  const result = [];
  let currentGroup = null;
  let rowSpanCount = 1;

  for (let row of rows) {
    if (currentGroup !== row.problemSummary) {
      currentGroup = row.problemSummary;
      rowSpanCount = 1;
    } else {
      rowSpanCount++;
    }

    const newRow = { ...row, rowSpan: rowSpanCount === 1 ? 1 : 0 };
    if (rowSpanCount === 1) {
      newRow.rowSpanActual = rowSpanCount;
      result.push(newRow);
    } else {
      result[result.length - 1].rowSpanActual = rowSpanCount;
    }
  }

  return result;
});

// 生成序号
function generateSerialNumbers(data) {
  return data.map((_, index) => index + 1);
}

const serialNumbers = computed(() =>
  generateSerialNumbers(mergedRowSpans.value)
);
</script>
<style>
.bordered-table {
  width: 100%;
  height: 450px;
  border-collapse: collapse;
}
.bordered-table th,
.bordered-table td {
  border: 1px solid black;
  padding: 5px;
}
.centered-input {
  text-align: center; /* 水平居中 */
}
</style>
